package com.xzy.service;

import com.spring.BeanPostProcessor;
import com.spring.Component;

import java.lang.reflect.InvocationHandler;
import java.lang.reflect.Method;
import java.lang.reflect.Proxy;

/**
 * @author xzy
 * @date 2021/11/415:15
 */
@Component("userAop")
public class UserAop implements BeanPostProcessor {

    @Override
    public Object postProcessAfterInitialization(Object bean, String beanName) throws Exception {
        if (bean instanceof UserService) {
            // 基于动态代理的AOP
            return Proxy.newProxyInstance(UserAop.class.getClassLoader(), new Class[]{UserService.class}, new InvocationHandler() {
                @Override
                public Object invoke(Object proxy, Method method, Object[] args) throws Throwable {
                    // 搞事...
                    System.out.println("...调用" + method.getName() + "前搞事...");

                    // 调用原方法
                    Object invoke = method.invoke(bean, args);

                    // 搞事...
                    System.out.println("...调用" + method.getName() + "后搞事...");
                    return invoke;
                }
            });
        }

        return bean;
    }
}
